#pragma once

#include <iostream>
#include <memory>
#include <unistd.h>
#include <poll.h>
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

class PollServer
{
    const static int size = 4096;
    const static int defaultfd = -1;

public:
    PollServer(int port) : _listensock(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        // 1. 创建套接字并绑定端口号并开始进行监听
        _listensock->BuildTcpSocketMethod(port);

        // 2. 将 pollfd 数组中的 fd 全部默认设置为 -1
        for (int i = 0; i < size; ++i)
            _fds[i].fd = defaultfd;

        // 3. 将  pollfd 数组中首元素的 fd 设置为监听套接字的 fd
        _fds[0].fd = _listensock->Fd();
        _fds[0].events = POLLIN;
    }

    void Start()
    {
        _isrunning = true;

        while (_isrunning)
        {
            PrintFd();
            int n = poll(_fds, size, -1);
            switch (n)
            {
            case -1:
                // poll 错误
                LOG(LogLevel::ERROR) << "poll error";
                break;
            case 0:
                // 2. poll 阻塞等待超时
                LOG(LogLevel::INFO) << "poll time out...";
                break;
            default:
                // 3. 读事件就绪（listen 套接字也是读事件就绪）
                LOG(LogLevel::DEBUG) << "读事件就绪..., n: " << n;
                Dispatcher(); // 进行事件派发
                break;
            }
        }

        _isrunning = false;
    }

    void Stop()
    {
        _isrunning = false;
    }

    ~PollServer() {}

    // 事件派发器
    void Dispatcher()
    {
        for (int i = 0; i < size; ++i)
        {
            // 1. 排除不合法的 fd
            if (_fds[i].fd == defaultfd)
                continue;
            // 2. 将合法且就绪的 fd 进行事件派发
            if (_fds[i].revents & POLLIN)
            {
                if (_fds[i].fd == _listensock->Fd())
                    Accepter();
                else
                    Recver(i);
            }
        }
    }

    // 连接管理器
    void Accepter()
    {
        InetAddr client;
        int sockfd = _listensock->Accept(&client); // 此时的 accept 不会被阻塞
        if (sockfd >= 0)
        {
            LOG(LogLevel::INFO) << "get a new link, sockfd: " << sockfd << ", client is: " << client.StringAddr();
            // 将新连接托管给 select
            int pos = 0;
            for (; pos < size; ++pos)
                if (_fds[pos].fd == defaultfd)
                    break;

            if (pos == size)
            {
                LOG(LogLevel::WARNING) << "poll server full";
                close(sockfd);
            }
            else {
                _fds[pos].fd = sockfd;
                _fds[pos].events = POLLIN;
                _fds[pos].revents = 0;
            }
        }
    }

    // IO处理器
    void Recver(int pos)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[pos].fd, buffer, sizeof(buffer) - 1, 0); // 这里读的时候会有 bug，不能保证一次读取全部的数据
        if (n > 0)
        {
            // 1. 读取到客户端传入的数据
            buffer[n] = 0;
            std::cout << "sockfd: " << _fds[pos].fd << ", client say@ " << buffer << std::endl;
        }
        else if (n == 0)
        {
            // 2. 客户端退出 -- 关闭连接并将其 fd 从 pollfd 数组中移除
            LOG(LogLevel::INFO) << "sockfd: " << _fds[pos].fd << ", client quit...";
            close(_fds[pos].fd);

            _fds[pos].fd = defaultfd;
            _fds[pos].events = 0;
            _fds[pos].revents = 0;
        }
        else
        {
            // 3. 读取出错 -- 关闭连接并将其 fd 从 pollfd 数组中移除
            LOG(LogLevel::ERROR) << "recv error";
            close(_fds[pos].fd);

            _fds[pos].fd = defaultfd;
            _fds[pos].events = 0;
            _fds[pos].revents = 0;
        }
    }

    void PrintFd()
    {
        std::cout << "_fds[].fd: ";
        for (int i = 0; i < size; ++i)
            if (_fds[i].fd != defaultfd)
                std::cout << _fds[i].fd << " ";
        std::cout << std::endl;
    }

private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;
    pollfd _fds[size];
};